{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f26a4ba9-f29b-452a-85c0-3b2a188f2348",
   "metadata": {},
   "source": [
    "# LangChain Expression Language Cheatsheet\n",
    "\n",
    "This is a quick reference for all the most important LCEL primitives. For more advanced usage see the [LCEL how-to guides](/docs/how_to/#langchain-expression-language-lcel) and the [full API reference](https://api.js.langchain.com/classes/langchain_core.runnables.Runnable.html).\n",
    "\n",
    "### Invoke a runnable\n",
    "#### [runnable.invoke()](https://api.js.langchain.com/classes/langchain_core.runnables.Runnable.html#invoke)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "b3ac3ad1-3c0e-4279-8fde-125809af9d2a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\u001b[32m\"5\"\u001b[39m"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import { RunnableLambda } from \"@langchain/core/runnables\";\n",
    "\n",
    "const runnable = RunnableLambda.from((x: number) => x.toString());\n",
    "\n",
    "await runnable.invoke(5);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aa74c79a-1bf6-4015-84bc-d0df6e6a8433",
   "metadata": {},
   "source": [
    "### Batch a runnable\n",
    "#### [runnable.batch()](hhttps://api.js.langchain.com/classes/langchain_core.runnables.Runnable.html#batch)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3a184890-da09-4ff7-92f9-0d29ca571ae4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[ \u001b[32m\"7\"\u001b[39m, \u001b[32m\"8\"\u001b[39m, \u001b[32m\"9\"\u001b[39m ]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import { RunnableLambda } from \"@langchain/core/runnables\";\n",
    "\n",
    "const runnable = RunnableLambda.from((x: number) => x.toString());\n",
    "\n",
    "await runnable.batch([7, 8, 9]);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b716b97f-cb58-447a-bef5-96202563cd2d",
   "metadata": {},
   "source": [
    "### Stream a runnable\n",
    "#### [runnable.stream()](https://api.js.langchain.com/classes/langchain_core.runnables.Runnable.html#stream)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "983aa18b-e44d-4603-aaea-94e1e2339001",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "---\n",
      "1\n",
      "---\n",
      "2\n",
      "---\n",
      "3\n",
      "---\n",
      "4\n",
      "---\n"
     ]
    }
   ],
   "source": [
    "import { RunnableLambda } from \"@langchain/core/runnables\";\n",
    "\n",
    "async function* generatorFn(x: number[]) {\n",
    "  for (const i of x) {\n",
    "    yield i.toString();\n",
    "  }\n",
    "}\n",
    "\n",
    "const runnable = RunnableLambda.from(generatorFn);\n",
    "\n",
    "const stream = await runnable.stream([0, 1, 2, 3, 4]);\n",
    "\n",
    "for await (const chunk of stream) {\n",
    "  console.log(chunk);\n",
    "  console.log(\"---\")\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6dc6bd08-98f3-4df6-9758-08b443e4328b",
   "metadata": {},
   "source": [
    "### Compose runnables\n",
    "#### [runnable.pipe()](https://api.js.langchain.com/classes/langchain_core.runnables.Runnable.html#pipe)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "4f744b0b-16ae-43f5-9856-789973457c96",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[ { foo: \u001b[33m2\u001b[39m }, { foo: \u001b[33m2\u001b[39m } ]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import { RunnableLambda } from \"@langchain/core/runnables\";\n",
    "\n",
    "const runnable1 = RunnableLambda.from((x: any) => {\n",
    "  return { foo: x };\n",
    "});\n",
    "\n",
    "const runnable2 = RunnableLambda.from((x: any) => [x].concat([x]));\n",
    "\n",
    "const chain = runnable1.pipe(runnable2);\n",
    "\n",
    "await chain.invoke(2);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "889be087",
   "metadata": {},
   "source": [
    "#### [RunnableSequence.from()](https://api.js.langchain.com/classes/langchain_core.runnables.RunnableSequence.html#from)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "cc601361",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[ { foo: \u001b[33m2\u001b[39m }, { foo: \u001b[33m2\u001b[39m } ]"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import { RunnableLambda, RunnableSequence } from \"@langchain/core/runnables\";\n",
    "\n",
    "const runnable1 = RunnableLambda.from((x: any) => {\n",
    "  return { foo: x };\n",
    "});\n",
    "\n",
    "const runnable2 = RunnableLambda.from((x: any) => [x].concat([x]));\n",
    "\n",
    "const chain = RunnableSequence.from([\n",
    "  runnable1,\n",
    "  runnable2,\n",
    "]);\n",
    "\n",
    "await chain.invoke(2);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b01e8694-f820-4457-a27a-7220f789bb2c",
   "metadata": {},
   "source": [
    "### Invoke runnables in parallel\n",
    "#### [RunnableParallel](https://api.js.langchain.com/classes/langchain_core.runnables.RunnableParallel.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "89e509e5-a9a5-4e56-b6dd-c4f23543c3c8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{ first: { foo: \u001b[33m2\u001b[39m }, second: [ \u001b[33m2\u001b[39m, \u001b[33m2\u001b[39m ] }"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import { RunnableLambda, RunnableParallel } from \"@langchain/core/runnables\";\n",
    "\n",
    "const runnable1 = RunnableLambda.from((x: any) => {\n",
    "  return { foo: x };\n",
    "});\n",
    "\n",
    "const runnable2 = RunnableLambda.from((x: any) => [x].concat([x]));\n",
    "\n",
    "const chain = RunnableParallel.from({\n",
    "  first: runnable1,\n",
    "  second: runnable2,\n",
    "});\n",
    "\n",
    "await chain.invoke(2);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "103f350b-84b3-421f-b64f-c01575a422bf",
   "metadata": {},
   "source": [
    "### Turn a function into a runnable\n",
    "#### [RunnableLambda](https://api.js.langchain.com/classes/langchain_core.runnables.RunnableLambda.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "a9c0e43a-8eb5-4985-ad95-43f12c3e05e9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\u001b[33m10\u001b[39m"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import { RunnableLambda } from \"@langchain/core/runnables\";\n",
    "\n",
    "const adder = (x: number) => {\n",
    "  return x + 5;\n",
    "};\n",
    "\n",
    "const runnable = RunnableLambda.from(adder);\n",
    "\n",
    "await runnable.invoke(5);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20399b82-e417-403d-a53b-00f02a6ef2c6",
   "metadata": {},
   "source": [
    "### Merge input and output dicts\n",
    "#### [RunnablePassthrough.assign()](https://api.js.langchain.com/classes/langchain_core.runnables.RunnablePassthrough.html#assign)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "ab05d376-9abb-4f26-916a-9aea062e4817",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{ foo: \u001b[33m10\u001b[39m, bar: \u001b[33m17\u001b[39m }"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import { RunnableLambda, RunnablePassthrough } from \"@langchain/core/runnables\";\n",
    "\n",
    "const runnable = RunnableLambda.from((x: { foo: number }) => {\n",
    "  return x.foo + 7;\n",
    "});\n",
    "\n",
    "const chain = RunnablePassthrough.assign({\n",
    "  bar: runnable,\n",
    "});\n",
    "\n",
    "await chain.invoke({ foo: 10 });"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f680f48-654a-44d1-86e3-13e1eb0955cb",
   "metadata": {},
   "source": [
    "### Include input dict in output dict\n",
    "\n",
    "#### [RunnablePassthrough](https://api.js.langchain.com/classes/langchain_core.runnables.RunnablePassthrough.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "3ec00283-e674-461e-a5d1-4876555a2a58",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{ baz: { foo: \u001b[33m10\u001b[39m }, bar: \u001b[33m17\u001b[39m }"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import {\n",
    "  RunnableLambda,\n",
    "  RunnableParallel,\n",
    "  RunnablePassthrough\n",
    "} from \"@langchain/core/runnables\";\n",
    "\n",
    "const runnable = RunnableLambda.from((x: { foo: number }) => {\n",
    "  return x.foo + 7;\n",
    "});\n",
    "\n",
    "const chain = RunnableParallel.from({\n",
    "  bar: runnable,\n",
    "  baz: new RunnablePassthrough(),\n",
    "});\n",
    "\n",
    "await chain.invoke({ foo: 10 });"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "baa4e967-fcfd-4176-a720-6916fe0df130",
   "metadata": {},
   "source": [
    "### Add default invocation args\n",
    "\n",
    "#### [runnable.bind()](https://api.js.langchain.com/classes/langchain_core.runnables.Runnable.html#bind)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "6c03ce55-5258-4361-857e-d6785c968624",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{ bar: \u001b[32m\"hello\"\u001b[39m, boundKey: \u001b[32m\"goodbye!\"\u001b[39m }"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import { type RunnableConfig, RunnableLambda } from \"@langchain/core/runnables\";\n",
    "\n",
    "const branchedFn = (mainArg: Record<string, any>, config?: RunnableConfig) => {\n",
    "  if (config?.configurable?.boundKey !== undefined) {\n",
    "    return { ...mainArg, boundKey: config?.configurable?.boundKey };\n",
    "  }\n",
    "  return mainArg;\n",
    "}\n",
    "\n",
    "const runnable = RunnableLambda.from(branchedFn);\n",
    "const boundRunnable = runnable.bind({ configurable: { boundKey: \"goodbye!\" } });\n",
    "\n",
    "await boundRunnable.invoke({ bar: \"hello\" });"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cad5e0af-007e-47aa-93d4-f06bd837c3fb",
   "metadata": {},
   "source": [
    "### Add fallbacks\n",
    "\n",
    "#### [runnable.withFallbacks()](https://api.js.langchain.com/classes/langchain_core.runnables.Runnable.html#withFallbacks)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "5d132d96-802b-4952-a6cc-2caaf4612d0a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\u001b[32m\"foofoo\"\u001b[39m"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import { RunnableLambda } from \"@langchain/core/runnables\";\n",
    "\n",
    "const runnable = RunnableLambda.from((x: any) => {\n",
    "  throw new Error(\"Error case\")\n",
    "});\n",
    "\n",
    "const fallback = RunnableLambda.from((x: any) => x + x);\n",
    "\n",
    "const chain = runnable.withFallbacks([fallback]);\n",
    "\n",
    "await chain.invoke(\"foo\");"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "809f6437-4e20-48b9-bdcb-7f9ea6463a19",
   "metadata": {},
   "source": [
    "### Add retries\n",
    "#### [runnable.withRetry()](https://api.js.langchain.com/classes/langchain_core.runnables.Runnable.html#withRetry)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "49a75c66-d335-4115-9d8f-ca07d69223c4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "attempt with counter 1\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "attempt with counter 2\n"
     ]
    },
    {
     "ename": "Error",
     "evalue": "Expected error",
     "output_type": "error",
     "traceback": [
      "Stack trace:",
      "Error: Expected error",
      "    at RunnableLambda.retryFn [as func] (<anonymous>:6:9)",
      "    at file:///Users/jacoblee/Library/Caches/deno/npm/registry.npmjs.org/@langchain/core/0.2.0/dist/runnables/base.js:1337:45",
      "    at MockAsyncLocalStorage.run (file:///Users/jacoblee/Library/Caches/deno/npm/registry.npmjs.org/@langchain/core/0.2.0/dist/singletons/index.js:7:16)",
      "    at file:///Users/jacoblee/Library/Caches/deno/npm/registry.npmjs.org/@langchain/core/0.2.0/dist/runnables/base.js:1335:67",
      "    at new Promise (<anonymous>)",
      "    at RunnableLambda._invoke (file:///Users/jacoblee/Library/Caches/deno/npm/registry.npmjs.org/@langchain/core/0.2.0/dist/runnables/base.js:1330:16)",
      "    at RunnableLambda._callWithConfig (file:///Users/jacoblee/Library/Caches/deno/npm/registry.npmjs.org/@langchain/core/0.2.0/dist/runnables/base.js:207:33)",
      "    at eventLoopTick (ext:core/01_core.js:78:9)",
      "    at async RetryOperation._fn (file:///Users/jacoblee/Library/Caches/deno/npm/registry.npmjs.org/p-retry/4.6.2/index.js:50:12)"
     ]
    }
   ],
   "source": [
    "import { RunnableLambda } from \"@langchain/core/runnables\";\n",
    "\n",
    "let counter = 0;\n",
    "\n",
    "const retryFn = (_: any) => {\n",
    "  counter++;\n",
    "  console.log(`attempt with counter ${counter}`);\n",
    "  throw new Error(\"Expected error\");\n",
    "};\n",
    "\n",
    "const chain = RunnableLambda.from(retryFn).withRetry({\n",
    "  stopAfterAttempt: 2,\n",
    "});\n",
    "\n",
    "await chain.invoke(2);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "741934ee-e97f-497d-b42f-371c79739a12",
   "metadata": {},
   "source": [
    "### Configure runnable execution\n",
    "\n",
    "#### [RunnableConfig](https://api.js.langchain.com/interfaces/langchain_core.runnables.RunnableConfig.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "d85e357e-c125-4199-98d1-bd0db40e4ac0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[ { foo: \u001b[33m1\u001b[39m }, { foo: \u001b[33m2\u001b[39m }, { foo: \u001b[33m3\u001b[39m } ]"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import { RunnableLambda } from \"@langchain/core/runnables\";\n",
    "\n",
    "const runnable1 = RunnableLambda.from(async (x: any) => {\n",
    "  await new Promise((resolve) => setTimeout(resolve, 2000));\n",
    "  return { foo: x };\n",
    "});\n",
    "\n",
    "// Takes 4 seconds\n",
    "await runnable1.batch([1, 2, 3], { maxConcurrency: 2 });"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8604edb4-4ffa-4cc7-89ba-e0c6947118ab",
   "metadata": {},
   "source": [
    "### Add default config to runnable\n",
    "\n",
    "#### [runnable.withConfig()](https://api.js.langchain.com/classes/langchain_core.runnables.Runnable.html#withConfig)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "dfe8306c-d77c-479a-90ae-464db2b62605",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[ { foo: \u001b[33m1\u001b[39m }, { foo: \u001b[33m2\u001b[39m }, { foo: \u001b[33m3\u001b[39m } ]"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import { RunnableLambda } from \"@langchain/core/runnables\";\n",
    "\n",
    "const runnable1 = RunnableLambda.from(async (x: any) => {\n",
    "  await new Promise((resolve) => setTimeout(resolve, 2000));\n",
    "  return { foo: x };\n",
    "}).withConfig({\n",
    "  maxConcurrency: 2,\n",
    "});\n",
    "\n",
    "// Takes 4 seconds\n",
    "await runnable1.batch([1, 2, 3]);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "33249dee-14dc-4c72-b6ba-a3f10678ab9c",
   "metadata": {},
   "source": [
    "### Build a chain dynamically based on input"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "4611b7ad-c29c-446c-8886-324bfd00eb41",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{ foo: \u001b[33m7\u001b[39m }"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import { RunnableLambda } from \"@langchain/core/runnables\";\n",
    "\n",
    "const runnable1 = RunnableLambda.from((x: any) => {\n",
    "  return { foo: x };\n",
    "});\n",
    "\n",
    "const runnable2 = RunnableLambda.from((x: any) => [x].concat([x]));\n",
    "\n",
    "const chain = RunnableLambda.from((x: number): any => {\n",
    "  if (x > 6) {\n",
    "    return runnable1;\n",
    "  }\n",
    "  return runnable2;\n",
    "});\n",
    "\n",
    "await chain.invoke(7);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "9655f494-2fba-4c26-a5d8-5683cc61e80d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[ \u001b[33m5\u001b[39m, \u001b[33m5\u001b[39m ]"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "await chain.invoke(5);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f1263fe5-6561-419b-a936-687f8b274a5d",
   "metadata": {},
   "source": [
    "### Generate a stream of internal events\n",
    "#### [runnable.streamEvents()](https://api.js.langchain.com/classes/langchain_core.runnables.Runnable.html#streamEvents)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "1988b1b2-b189-43c9-8ffd-d7f275881065",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "event=on_chain_start | name=RunnableSequence | data={\"input\":2}\n",
      "event=on_chain_start | name=first | data={}\n",
      "event=on_chain_stream | name=first | data={\"chunk\":{\"foo\":2}}\n",
      "event=on_chain_start | name=second | data={}\n",
      "event=on_chain_end | name=first | data={\"input\":2,\"output\":{\"foo\":2}}\n",
      "event=on_chain_stream | name=second | data={\"chunk\":\"0\"}\n",
      "event=on_chain_stream | name=RunnableSequence | data={\"chunk\":\"0\"}\n",
      "event=on_chain_stream | name=second | data={\"chunk\":\"1\"}\n",
      "event=on_chain_stream | name=RunnableSequence | data={\"chunk\":\"1\"}\n",
      "event=on_chain_end | name=second | data={\"output\":\"01\"}\n",
      "event=on_chain_end | name=RunnableSequence | data={\"output\":\"01\"}\n"
     ]
    }
   ],
   "source": [
    "import { RunnableLambda } from \"@langchain/core/runnables\";\n",
    "\n",
    "const runnable1 = RunnableLambda.from((x: number) => {\n",
    "  return {\n",
    "    foo: x,\n",
    "  };\n",
    "}).withConfig({\n",
    "  runName: \"first\",\n",
    "});\n",
    "\n",
    "async function* generatorFn(x: { foo: number }) {\n",
    "  for (let i = 0; i < x.foo; i++) {\n",
    "    yield i.toString();\n",
    "  }\n",
    "}\n",
    "\n",
    "const runnable2 = RunnableLambda.from(generatorFn).withConfig({\n",
    "  runName: \"second\",\n",
    "});\n",
    "\n",
    "const chain = runnable1.pipe(runnable2);\n",
    "\n",
    "for await (const event of chain.streamEvents(2, { version: \"v1\" })) {\n",
    "  console.log(`event=${event.event} | name=${event.name} | data=${JSON.stringify(event.data)}`);\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc1cacde-b35e-474a-a14a-ed9e8a858ba8",
   "metadata": {},
   "source": [
    "### Return a subset of keys from output object\n",
    "\n",
    "#### [runnable.pick()](https://api.js.langchain.com/classes/langchain_core.runnables.Runnable.html#pick)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "78dd3ed5-5095-4698-ba4f-d0b73f12a608",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{ foo: \u001b[33m7\u001b[39m, bar: \u001b[32m\"hi\"\u001b[39m }"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import { RunnableLambda, RunnablePassthrough } from \"@langchain/core/runnables\";\n",
    "\n",
    "const runnable = RunnableLambda.from((x: { baz: number }) => {\n",
    "  return x.baz + 5;\n",
    "});\n",
    "\n",
    "const chain = RunnablePassthrough.assign({\n",
    "  foo: runnable,\n",
    "}).pick([\"foo\", \"bar\"]);\n",
    "\n",
    "await chain.invoke({\"bar\": \"hi\", \"baz\": 2});"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5587dbda-d6d7-4480-b2e9-7541af076d36",
   "metadata": {},
   "source": [
    "### Declaratively make a batched version of a runnable\n",
    "\n",
    "#### [`runnable.map()`](https://api.js.langchain.com/classes/langchain_core.runnables.Runnable.html#map)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "fd020416-faf0-4343-945c-823d879d8431",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[ \u001b[33m5\u001b[39m, \u001b[33m6\u001b[39m, \u001b[33m7\u001b[39m ]"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import { RunnableLambda } from \"@langchain/core/runnables\";\n",
    "\n",
    "const runnable1 = RunnableLambda.from((x: number) => [...Array(x).keys()]);\n",
    "const runnable2 = RunnableLambda.from((x: number) => x + 5);\n",
    "\n",
    "const chain = runnable1.pipe(runnable2.map());\n",
    "\n",
    "await chain.invoke(3);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e4ed5c3-244e-4491-adbe-83af3fc14265",
   "metadata": {},
   "source": [
    "### Get a graph representation of a runnable\n",
    "\n",
    "#### [runnable.getGraph()](https://api.js.langchain.com/classes/langchain_core.runnables.Runnable.html#getGraph)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "11ef1419-a2ee-41bd-a74f-c057a6d737ac",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Graph {\n",
       "  nodes: {\n",
       "    \u001b[32m\"935c67df-7ae3-4853-9d26-579003c08407\"\u001b[39m: {\n",
       "      id: \u001b[32m\"935c67df-7ae3-4853-9d26-579003c08407\"\u001b[39m,\n",
       "      data: {\n",
       "        name: \u001b[32m\"RunnableLambdaInput\"\u001b[39m,\n",
       "        schema: ZodAny {\n",
       "          spa: \u001b[36m[Function: bound safeParseAsync] AsyncFunction\u001b[39m,\n",
       "          _def: \u001b[36m[Object]\u001b[39m,\n",
       "          parse: \u001b[36m[Function: bound parse]\u001b[39m,\n",
       "          safeParse: \u001b[36m[Function: bound safeParse]\u001b[39m,\n",
       "          parseAsync: \u001b[36m[Function: bound parseAsync] AsyncFunction\u001b[39m,\n",
       "          safeParseAsync: \u001b[36m[Function: bound safeParseAsync] AsyncFunction\u001b[39m,\n",
       "          refine: \u001b[36m[Function: bound refine]\u001b[39m,\n",
       "          refinement: \u001b[36m[Function: bound refinement]\u001b[39m,\n",
       "          superRefine: \u001b[36m[Function: bound superRefine]\u001b[39m,\n",
       "          optional: \u001b[36m[Function: bound optional]\u001b[39m,\n",
       "          nullable: \u001b[36m[Function: bound nullable]\u001b[39m,\n",
       "          nullish: \u001b[36m[Function: bound nullish]\u001b[39m,\n",
       "          array: \u001b[36m[Function: bound array]\u001b[39m,\n",
       "          promise: \u001b[36m[Function: bound promise]\u001b[39m,\n",
       "          or: \u001b[36m[Function: bound or]\u001b[39m,\n",
       "          and: \u001b[36m[Function: bound and]\u001b[39m,\n",
       "          transform: \u001b[36m[Function: bound transform]\u001b[39m,\n",
       "          brand: \u001b[36m[Function: bound brand]\u001b[39m,\n",
       "          default: \u001b[36m[Function: bound default]\u001b[39m,\n",
       "          catch: \u001b[36m[Function: bound catch]\u001b[39m,\n",
       "          describe: \u001b[36m[Function: bound describe]\u001b[39m,\n",
       "          pipe: \u001b[36m[Function: bound pipe]\u001b[39m,\n",
       "          readonly: \u001b[36m[Function: bound readonly]\u001b[39m,\n",
       "          isNullable: \u001b[36m[Function: bound isNullable]\u001b[39m,\n",
       "          isOptional: \u001b[36m[Function: bound isOptional]\u001b[39m,\n",
       "          _any: \u001b[33mtrue\u001b[39m\n",
       "        }\n",
       "      }\n",
       "    },\n",
       "    \u001b[32m\"a73d7b3e-0ed7-46cf-b141-de64ea1e12de\"\u001b[39m: {\n",
       "      id: \u001b[32m\"a73d7b3e-0ed7-46cf-b141-de64ea1e12de\"\u001b[39m,\n",
       "      data: RunnableLambda {\n",
       "        lc_serializable: \u001b[33mfalse\u001b[39m,\n",
       "        lc_kwargs: { func: \u001b[36m[Function (anonymous)]\u001b[39m },\n",
       "        lc_runnable: \u001b[33mtrue\u001b[39m,\n",
       "        name: \u001b[90mundefined\u001b[39m,\n",
       "        lc_namespace: [ \u001b[32m\"langchain_core\"\u001b[39m, \u001b[32m\"runnables\"\u001b[39m ],\n",
       "        func: \u001b[36m[Function (anonymous)]\u001b[39m\n",
       "      }\n",
       "    },\n",
       "    \u001b[32m\"ff104b34-c13b-4677-8b82-af70d3548e12\"\u001b[39m: {\n",
       "      id: \u001b[32m\"ff104b34-c13b-4677-8b82-af70d3548e12\"\u001b[39m,\n",
       "      data: RunnableMap {\n",
       "        lc_serializable: \u001b[33mtrue\u001b[39m,\n",
       "        lc_kwargs: { steps: \u001b[36m[Object]\u001b[39m },\n",
       "        lc_runnable: \u001b[33mtrue\u001b[39m,\n",
       "        name: \u001b[90mundefined\u001b[39m,\n",
       "        lc_namespace: [ \u001b[32m\"langchain_core\"\u001b[39m, \u001b[32m\"runnables\"\u001b[39m ],\n",
       "        steps: { second: \u001b[36m[RunnableLambda]\u001b[39m, third: \u001b[36m[RunnableLambda]\u001b[39m }\n",
       "      }\n",
       "    },\n",
       "    \u001b[32m\"2dc627dc-1c06-45b1-b14f-bb1f6e689f83\"\u001b[39m: {\n",
       "      id: \u001b[32m\"2dc627dc-1c06-45b1-b14f-bb1f6e689f83\"\u001b[39m,\n",
       "      data: {\n",
       "        name: \u001b[32m\"RunnableMapOutput\"\u001b[39m,\n",
       "        schema: ZodAny {\n",
       "          spa: \u001b[36m[Function: bound safeParseAsync] AsyncFunction\u001b[39m,\n",
       "          _def: \u001b[36m[Object]\u001b[39m,\n",
       "          parse: \u001b[36m[Function: bound parse]\u001b[39m,\n",
       "          safeParse: \u001b[36m[Function: bound safeParse]\u001b[39m,\n",
       "          parseAsync: \u001b[36m[Function: bound parseAsync] AsyncFunction\u001b[39m,\n",
       "          safeParseAsync: \u001b[36m[Function: bound safeParseAsync] AsyncFunction\u001b[39m,\n",
       "          refine: \u001b[36m[Function: bound refine]\u001b[39m,\n",
       "          refinement: \u001b[36m[Function: bound refinement]\u001b[39m,\n",
       "          superRefine: \u001b[36m[Function: bound superRefine]\u001b[39m,\n",
       "          optional: \u001b[36m[Function: bound optional]\u001b[39m,\n",
       "          nullable: \u001b[36m[Function: bound nullable]\u001b[39m,\n",
       "          nullish: \u001b[36m[Function: bound nullish]\u001b[39m,\n",
       "          array: \u001b[36m[Function: bound array]\u001b[39m,\n",
       "          promise: \u001b[36m[Function: bound promise]\u001b[39m,\n",
       "          or: \u001b[36m[Function: bound or]\u001b[39m,\n",
       "          and: \u001b[36m[Function: bound and]\u001b[39m,\n",
       "          transform: \u001b[36m[Function: bound transform]\u001b[39m,\n",
       "          brand: \u001b[36m[Function: bound brand]\u001b[39m,\n",
       "          default: \u001b[36m[Function: bound default]\u001b[39m,\n",
       "          catch: \u001b[36m[Function: bound catch]\u001b[39m,\n",
       "          describe: \u001b[36m[Function: bound describe]\u001b[39m,\n",
       "          pipe: \u001b[36m[Function: bound pipe]\u001b[39m,\n",
       "          readonly: \u001b[36m[Function: bound readonly]\u001b[39m,\n",
       "          isNullable: \u001b[36m[Function: bound isNullable]\u001b[39m,\n",
       "          isOptional: \u001b[36m[Function: bound isOptional]\u001b[39m,\n",
       "          _any: \u001b[33mtrue\u001b[39m\n",
       "        }\n",
       "      }\n",
       "    }\n",
       "  },\n",
       "  edges: [\n",
       "    {\n",
       "      source: \u001b[32m\"935c67df-7ae3-4853-9d26-579003c08407\"\u001b[39m,\n",
       "      target: \u001b[32m\"a73d7b3e-0ed7-46cf-b141-de64ea1e12de\"\u001b[39m,\n",
       "      data: \u001b[90mundefined\u001b[39m\n",
       "    },\n",
       "    {\n",
       "      source: \u001b[32m\"ff104b34-c13b-4677-8b82-af70d3548e12\"\u001b[39m,\n",
       "      target: \u001b[32m\"2dc627dc-1c06-45b1-b14f-bb1f6e689f83\"\u001b[39m,\n",
       "      data: \u001b[90mundefined\u001b[39m\n",
       "    },\n",
       "    {\n",
       "      source: \u001b[32m\"a73d7b3e-0ed7-46cf-b141-de64ea1e12de\"\u001b[39m,\n",
       "      target: \u001b[32m\"ff104b34-c13b-4677-8b82-af70d3548e12\"\u001b[39m,\n",
       "      data: \u001b[90mundefined\u001b[39m\n",
       "    }\n",
       "  ]\n",
       "}"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import { RunnableLambda, RunnableSequence } from \"@langchain/core/runnables\";\n",
    "\n",
    "const runnable1 = RunnableLambda.from((x: any) => {\n",
    "  return { foo: x };\n",
    "});\n",
    "\n",
    "const runnable2 = RunnableLambda.from((x: any) => [x].concat([x]));\n",
    "\n",
    "const runnable3 = RunnableLambda.from((x: any) => x.toString());\n",
    "\n",
    "const chain = RunnableSequence.from([\n",
    "  runnable1,\n",
    "  {\n",
    "    second: runnable2,\n",
    "    third: runnable3,\n",
    "  }\n",
    "]);\n",
    "\n",
    "await chain.getGraph();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "632c628d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Deno",
   "language": "typescript",
   "name": "deno"
  },
  "language_info": {
   "file_extension": ".ts",
   "mimetype": "text/x.typescript",
   "name": "typescript",
   "nb_converter": "script",
   "pygments_lexer": "typescript",
   "version": "5.3.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
